﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Net;
using System.Data;
using System.Threading;
using System.Configuration;


namespace DISPLAY_CLIENT
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public class Passage
        {
            public string PassageName;
            public string InOut;
            public string photo;
            public string staffno;
            public string cardno;
            public string name;
            public string org;
            public string job;
            public string job_lev;
            public bool Status;
            public int LiveTime;
            public bool Changed;
            
        }

        

        public Passage[] Passages = new Passage[15];

        private System.Threading.Timer Time_timer;
        private System.Threading.Timer Count_timer;
        private System.Threading.Timer staff_timer;

        DataTable Staff_dt = new DataTable();
        DataTable staffdt = new DataTable();
        int n = 0;
        Listener myListen = null;
        private static string wayname = ConfigurationManager.AppSettings["井口名称"];
        private static bool b_Download = (ConfigurationManager.AppSettings["人员照片下载"] != "0");
        private static string PhotoPath = ConfigurationManager.AppSettings["人员照片本地路径"];
        private static string FtpString = ConfigurationManager.AppSettings["人员照片FTP服务器"];
        private static bool b_PlayVoice = (ConfigurationManager.AppSettings["播放语音"] != "0");
        private static int LiveTime = int.Parse(ConfigurationManager.AppSettings["显示时长"]);
        private static string str_bc = ConfigurationManager.AppSettings["班次"];
        //新增窗口根据设备IP固定显示位置配置
        private static string window_1_1 = (ConfigurationManager.AppSettings["窗口1-1"]);
        private static string window_1_2 = (ConfigurationManager.AppSettings["窗口1-2"]);
        private static string window_1_3 = (ConfigurationManager.AppSettings["窗口1-3"]);
        private static string window_1_4 = (ConfigurationManager.AppSettings["窗口1-4"]);
        private static string window_1_5 = (ConfigurationManager.AppSettings["窗口1-5"]);
        private static string window_2_1 = (ConfigurationManager.AppSettings["窗口2-1"]);
        private static string window_2_2 = (ConfigurationManager.AppSettings["窗口2-2"]);
        private static string window_2_3 = (ConfigurationManager.AppSettings["窗口2-3"]);
        private static string window_2_4 = (ConfigurationManager.AppSettings["窗口2-4"]);
        private static string window_2_5 = (ConfigurationManager.AppSettings["窗口2-5"]);
        private static string FtpUrl;
        private static string FtpUser;
        private static string FtpPwd;
        private Queue<string> MsgQue = new Queue<string>();
        private int MsgLiveTime;
        private dynamic spVoice;
        private string BeaconList = string.Empty;
        private class Time_bc
        {
            public int hour;
            public int minute;
        }
        private int re_swich;
        private long[] Com_time = new long[3];
        private List<Time_bc> list_schedule = new List<Time_bc>();
        private List<DateTime> time_schedule = new List<DateTime>();
        private List<int> incount_schedule = new List<int>();
        private List<int> outcount_schedule = new List<int>();
        private ListWindow WatchWnd;
        public bool ended = false;

        public MainWindow()
        {
            InitializeComponent();
            if (wayname.Length > 0)
            {
                lb_title.Content = wayname;
            }
            else
            {
                lb_title.Content = "迪迈门禁系统";
            }
            WatchWnd = new ListWindow(this);
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            FtpParse(FtpString);

            ////加载语音
            try
            {
                Type type = Type.GetTypeFromProgID("SAPI.SpVoice");
                spVoice = Activator.CreateInstance(type);
            }
            catch
            {
            }

            //解析班次
            if (str_bc.Length > 0)
            {
                
                int i = 0;
                string[] arr_bc = str_bc.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string one_bc in arr_bc)
                {
                    string[] arr_time = one_bc.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                    
                    Time_bc new_bc = new Time_bc();
                    new_bc.hour = int.Parse(arr_time[0]);
                    if (arr_time.Length > 1)
                    {
                        new_bc.minute = int.Parse(arr_time[1]);
                    }
                    else
                    {
                        new_bc.minute = 0;
                    }
                    list_schedule.Add(new_bc);
                    Com_time[i] = new_bc.hour * 60 * 60 + new_bc.minute * 60;
                    i++;
                }
            }
            else
            {
                Time_bc new_bc = new Time_bc();
                new_bc.hour = 0;
                new_bc.minute = 0;
                list_schedule.Add(new_bc);
            }

            Time_timer = new System.Threading.Timer(new TimerCallback(TimeTimer), null, 0, 1000);
            Count_timer = new System.Threading.Timer(new TimerCallback(GetCount), null, 0, 5000);
            staff_timer = new System.Threading.Timer(new TimerCallback(StaffTimer), null, 0, 210000);

            myListen = new Listener();
            myListen.onReceive += new Listener.OndataReceive(ParseMessage);
            try
            {
                if (!myListen.Register())
                {
                    MessageBox.Show("服务器未启动！", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    this.Close();
                }
                else
                {
                    if (myListen.ServerIP != "-")
                    {
                        myListen.StartListen();
                    }
                    else
                    {
                        WatchWnd.ShowData();
                    }
                }
            }
            catch { }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            myListen.StopListen();
            if (Time_timer != null)
            {
                Time_timer.Dispose();
            }
            if (Count_timer != null)
            {
                Count_timer.Dispose();
            }
            if (staff_timer != null)
            {
                staff_timer.Dispose();
            }
            ended = true;
            WatchWnd.Close();
        }

        private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            double titlesize = 45;
            System.Windows.Application.Current.Resources.Remove("TitleFontSize");
            System.Windows.Application.Current.Resources.Add("TitleFontSize", titlesize);
            double bigsize = this.Height / 65;
            System.Windows.Application.Current.Resources.Remove("BigFontSize");
            System.Windows.Application.Current.Resources.Add("BigFontSize", bigsize);
            double midsize = this.Height / 80;
            System.Windows.Application.Current.Resources.Remove("MidFontSize");
            System.Windows.Application.Current.Resources.Add("MidFontSize", midsize);
            double smallsize = this.Height / 90;
            System.Windows.Application.Current.Resources.Remove("SmallFontSize");
            System.Windows.Application.Current.Resources.Add("SmallFontSize", smallsize);
            //查询按钮字体
            double Query_button = this.Height / 35;
            System.Windows.Application.Current.Resources.Remove("Query_button");
            System.Windows.Application.Current.Resources.Add("Query_button", Query_button);
            //lastInOut_staff字体大小
            double lastInOut_staff = this.Height / 37;
            System.Windows.Application.Current.Resources.Remove("lastInOut_staff");
            System.Windows.Application.Current.Resources.Add("lastInOut_staff", lastInOut_staff);
            //时间字体
            double time_size = this.Height / 30;
            System.Windows.Application.Current.Resources.Remove("time_size");
            System.Windows.Application.Current.Resources.Add("time_size", time_size);
            //设备名称字体
            double BeaconName = this.Height / 35;
            System.Windows.Application.Current.Resources.Remove("BeaconName");
            System.Windows.Application.Current.Resources.Add("BeaconName", BeaconName);

            //人员信息显示字体
            double StaffSize = this.Height / 50;
            System.Windows.Application.Current.Resources.Remove("StaffSize");
            System.Windows.Application.Current.Resources.Add("StaffSize", StaffSize);
            if (WatchWnd != null)
            {
                WatchWnd.Width = this.Width * 0.995;
                WatchWnd.Height = (this.Height - 98) / 1.2 + 92*1.65;
                if (this.WindowState == WindowState.Maximized)
                {
                    WatchWnd.Left = 0;
                    WatchWnd.Top = 0;
                }
            }
        }

        private void Window_LocationChanged(object sender, EventArgs e)
        {
            if (WatchWnd != null)
            {
                WatchWnd.Left = this.Left;
                WatchWnd.Top = this.Top;
            }
        }

        private void Window_Activated(object sender, EventArgs e)
        {
            if ((WatchWnd != null) && (WatchWnd.Visibility == Visibility.Visible))
            {
                WatchWnd.Activate();
            }
        }

        private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount == 2)
            {
                if (this.WindowState == WindowState.Maximized)
                {
                    this.WindowState = WindowState.Normal;
                    this.Height = SystemParameters.PrimaryScreenHeight * 0.9;
                    this.Width = SystemParameters.PrimaryScreenWidth * 0.9;
                }
                else
                {
                    this.WindowState = WindowState.Maximized;
                }
            }
        }

        private void Border_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                this.DragMove();
            }
        }

        private void btn_close_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("是否确定要退出？", "退出", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
                return;
            this.Close();
        }

        private void btn_list_Click(object sender, RoutedEventArgs e)
        {
            WatchWnd.ShowData();
        }

        //解析FTP字符串
        private static void FtpParse(string FtpString)
        {
            string[] arrFtpString = FtpString.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < arrFtpString.Length; i++)
            {
                if (arrFtpString[i].IndexOf("url=") >= 0)
                {
                    FtpUrl = arrFtpString[i].Substring(4);
                }
                else if (arrFtpString[i].IndexOf("user=") >= 0)
                {
                    FtpUser = arrFtpString[i].Substring(5);
                }
                else if (arrFtpString[i].IndexOf("pwd=") >= 0)
                {
                    FtpPwd = arrFtpString[i].Substring(4);
                }
            }
        }

        //根据文件名获取照片，本地有则直接取本地，没有则从FTP下载
        public static string GetPhoto(string fileName)
        {
            FtpWebRequest reqFTP;
            try
            {
                if (fileName.Length <= 0)
                {
                    return "Images/Default.jpg";
                }
                string path = PhotoPath + fileName;

                if (File.Exists(path)) 
                {
                    return path;
                }

                if (!b_Download)
                {
                    return "Images/Default.jpg";
                }

                string directory = path.Substring(0, path.LastIndexOf('/'));
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(FtpUrl + fileName));
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.UsePassive = false;
                reqFTP.Credentials = new NetworkCredential(FtpUser, FtpPwd);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                long cl = response.ContentLength;
                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];

                readCount = ftpStream.Read(buffer, 0, bufferSize);

                if (readCount <= 0)
                {
                    ftpStream.Close();
                    response.Close();
                    return "Images/Default.jpg";
                }

                FileStream outputStream = new FileStream(path, FileMode.Create);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }

                ftpStream.Close();
                response.Close(); 
                outputStream.Close();
                return path;
            }
            catch
            {
                return "Images/Default.jpg";
            }
        }

        //出入井界面更新函数
        private void UpdateUI()
        {
            try
            {
                for (int i = 0;  i < 15; i++)
                {
                    if (Passages[i] != null && Passages[i].PassageName == window_1_1)
                    {
                        if (Passages[i].Changed)
                        {
                            if (Passages[i].LiveTime > 0)
                            {
                                img_photo_1.Source = new BitmapImage(new Uri(GetPhoto(Passages[i].photo), UriKind.RelativeOrAbsolute));
                                lb_staffno_1.Content = Passages[i].staffno;
                                lb_cardno_1.Content = Passages[i].cardno;
                                lb_name_1.Content = Passages[i].name;
                                lb_org_1.Content = Passages[i].org;
                                lb_job_1.Content = Passages[i].job;
                                lb_job_lev_1.Content = Passages[i].job_lev;
                            }
                            else
                            {
                                img_photo_1.Source = new BitmapImage(new Uri(GetPhoto(""), UriKind.RelativeOrAbsolute));
                                lb_staffno_1.Content = "";
                                lb_cardno_1.Content = "";
                                lb_name_1.Content = "";
                                lb_org_1.Content = "";
                                lb_job_1.Content = "";
                                lb_job_lev_1.Content = "";
                            }
                            Passages[i].Changed = false;
                        }
                    }
                }

                for (int i = 0;  i < 15; i++)
                {
                    if (Passages[i] != null && Passages[i].PassageName == window_1_2)
                    {
                        if (Passages[i].Changed)
                        {
                            if (Passages[i].LiveTime > 0)
                            {
                                img_photo_2.Source = new BitmapImage(new Uri(GetPhoto(Passages[i].photo), UriKind.RelativeOrAbsolute));
                                lb_staffno_2.Content = Passages[i].staffno;
                                lb_cardno_2.Content = Passages[i].cardno;
                                lb_name_2.Content = Passages[i].name;
                                lb_org_2.Content = Passages[i].org;
                                lb_job_2.Content = Passages[i].job;
                                lb_job_lev_2.Content = Passages[i].job_lev;
                            }
                            else
                            {
                                img_photo_2.Source = new BitmapImage(new Uri(GetPhoto(""), UriKind.RelativeOrAbsolute));
                                lb_staffno_2.Content = "";
                                lb_cardno_2.Content = "";
                                lb_name_2.Content = "";
                                lb_org_2.Content = "";
                                lb_job_2.Content = "";
                                lb_job_lev_2.Content = "";
                            }
                            Passages[i].Changed = false;
                        }
                    }
                }

                for (int i = 0;  i < 15; i++)
                {
                    if (Passages[i] != null && Passages[i].PassageName == window_1_3)
                    {
                        if (Passages[i].Changed)
                        {
                            if (Passages[i].LiveTime > 0)
                            {
                                img_photo_3.Source = new BitmapImage(new Uri(GetPhoto(Passages[i].photo), UriKind.RelativeOrAbsolute));
                                lb_staffno_3.Content = Passages[i].staffno;
                                lb_cardno_3.Content = Passages[i].cardno;
                                lb_name_3.Content = Passages[i].name;
                                lb_org_3.Content = Passages[i].org;
                                lb_job_3.Content = Passages[i].job;
                                lb_job_lev_3.Content = Passages[i].job_lev;
                            }
                            else
                            {
                                img_photo_3.Source = new BitmapImage(new Uri(GetPhoto(""), UriKind.RelativeOrAbsolute));
                                lb_staffno_3.Content = "";
                                lb_cardno_3.Content = "";
                                lb_name_3.Content = "";
                                lb_org_3.Content = "";
                                lb_job_3.Content = "";
                                lb_job_lev_3.Content = "";
                            }
                            Passages[i].Changed = false;
                        }
                    }
                }

                for (int i = 0; i < 15; i++)
                {
                    if (Passages[i] != null && Passages[i].PassageName == window_1_4)
                    {
                        if (Passages[i].Changed)
                        {
                            if (Passages[i].LiveTime > 0)
                            {
                                img_photo_4.Source = new BitmapImage(new Uri(GetPhoto(Passages[i].photo), UriKind.RelativeOrAbsolute));
                                lb_staffno_4.Content = Passages[i].staffno;
                                lb_cardno_4.Content = Passages[i].cardno;
                                lb_name_4.Content = Passages[i].name;
                                lb_org_4.Content = Passages[i].org;
                                lb_job_4.Content = Passages[i].job;
                                lb_job_lev_4.Content = Passages[i].job_lev;
                            }
                            else
                            {
                                img_photo_4.Source = new BitmapImage(new Uri(GetPhoto(""), UriKind.RelativeOrAbsolute));
                                lb_staffno_4.Content = "";
                                lb_cardno_4.Content = "";
                                lb_name_4.Content = "";
                                lb_org_4.Content = "";
                                lb_job_4.Content = "";
                                lb_job_lev_4.Content = "";
                            }
                            Passages[i].Changed = false;
                        }
                    }
                }

                for (int i = 0; i < 15; i++)
                {
                    if (Passages[i] != null && Passages[i].PassageName == window_1_5)
                    {
                        if (Passages[i].Changed)
                        {
                            if (Passages[i].LiveTime > 0)
                            {
                                img_photo_15.Source = new BitmapImage(new Uri(GetPhoto(Passages[i].photo), UriKind.RelativeOrAbsolute));
                                lb_staffno_15.Content = Passages[i].staffno;
                                lb_cardno_15.Content = Passages[i].cardno;
                                lb_name_15.Content = Passages[i].name;
                                lb_org_15.Content = Passages[i].org;
                                lb_job_15.Content = Passages[i].job;
                                lb_job_lev_15.Content = Passages[i].job_lev;
                            }
                            else
                            {
                                img_photo_15.Source = new BitmapImage(new Uri(GetPhoto(""), UriKind.RelativeOrAbsolute));
                                lb_staffno_15.Content = "";
                                lb_cardno_15.Content = "";
                                lb_name_15.Content = "";
                                lb_org_15.Content = "";
                                lb_job_15.Content = "";
                                lb_job_lev_15.Content = "";
                            }
                            Passages[i].Changed = false;
                        }
                    }
                }
                //第二行第1个
                for (int i = 0; i < 15; i++)
                {
                    if (Passages[i] != null && Passages[i].PassageName == window_2_1)
                    {
                        if (Passages[i].Changed)
                        {
                            if (Passages[i].LiveTime > 0)
                            {
                                img_photo_21.Source = new BitmapImage(new Uri(GetPhoto(Passages[i].photo), UriKind.RelativeOrAbsolute));
                                lb_staffno_21.Content = Passages[i].staffno;
                                lb_cardno_21.Content = Passages[i].cardno;
                                lb_name_21.Content = Passages[i].name;
                                lb_org_21.Content = Passages[i].org;
                                lb_job_21.Content = Passages[i].job;
                                lb_job_lev_21.Content = Passages[i].job_lev;
                            }
                            else
                            {
                                img_photo_21.Source = new BitmapImage(new Uri(GetPhoto(""), UriKind.RelativeOrAbsolute));
                                lb_staffno_21.Content = "";
                                lb_cardno_21.Content = "";
                                lb_name_21.Content = "";
                                lb_org_21.Content = "";
                                lb_job_21.Content = "";
                                lb_job_lev_21.Content = "";
                            }
                            Passages[i].Changed = false;
                        }
                    }
                }
                //第二行第2个
                for (int i = 0;  i < 15; i++)
                {
                    if (Passages[i] != null&& Passages[i].PassageName == window_2_2)
                    {
                        if (Passages[i].Changed)
                        {
                            if (Passages[i].LiveTime > 0)
                            {
                                img_photo_22.Source = new BitmapImage(new Uri(GetPhoto(Passages[i].photo), UriKind.RelativeOrAbsolute));
                                lb_staffno_22.Content = Passages[i].staffno;
                                lb_cardno_22.Content = Passages[i].cardno;
                                lb_name_22.Content = Passages[i].name;
                                lb_org_22.Content = Passages[i].org;
                                lb_job_22.Content = Passages[i].job;
                                lb_job_lev_22.Content = Passages[i].job_lev;
                            }
                            else
                            {
                                img_photo_22.Source = new BitmapImage(new Uri(GetPhoto(""), UriKind.RelativeOrAbsolute));
                                lb_staffno_22.Content = "";
                                lb_cardno_22.Content = "";
                                lb_name_22.Content = "";
                                lb_org_22.Content = "";
                                lb_job_22.Content = "";
                                lb_job_lev_22.Content = "";
                            }
                            Passages[i].Changed = false;
                        }
                    }
                }
                //第二行第3个
                for (int i = 0;  i < 15; i++)
                {
                    if (Passages[i] != null && Passages[i].PassageName == window_2_3)
                    {
                        if (Passages[i].Changed)
                        {
                            if (Passages[i].LiveTime > 0)
                            {
                                img_photo_23.Source = new BitmapImage(new Uri(GetPhoto(Passages[i].photo), UriKind.RelativeOrAbsolute));
                                lb_staffno_23.Content = Passages[i].staffno;
                                lb_cardno_23.Content = Passages[i].cardno;
                                lb_name_23.Content = Passages[i].name;
                                lb_org_23.Content = Passages[i].org;
                                lb_job_23.Content = Passages[i].job;
                                lb_job_lev_23.Content = Passages[i].job_lev;
                            }
                            else
                            {
                                img_photo_23.Source = new BitmapImage(new Uri(GetPhoto(""), UriKind.RelativeOrAbsolute));
                                lb_staffno_23.Content = "";
                                lb_cardno_23.Content = "";
                                lb_name_23.Content = "";
                                lb_org_23.Content = "";
                                lb_job_23.Content = "";
                                lb_job_lev_23.Content = "";
                            }
                            Passages[i].Changed = false;
                        }
                    }
                }
                //第二行第4个
                for (int i = 0; i < 15; i++)
                {
                    if (Passages[i] != null && Passages[i].PassageName == window_2_4)
                    {
                        if (Passages[i].Changed)
                        {
                            if (Passages[i].LiveTime > 0)
                            {
                                img_photo_24.Source = new BitmapImage(new Uri(GetPhoto(Passages[i].photo), UriKind.RelativeOrAbsolute));
                                lb_staffno_24.Content = Passages[i].staffno;
                                lb_cardno_24.Content = Passages[i].cardno;
                                lb_name_24.Content = Passages[i].name;
                                lb_org_24.Content = Passages[i].org;
                                lb_job_24.Content = Passages[i].job;
                                lb_job_lev_24.Content = Passages[i].job_lev;
                            }
                            else
                            {
                                img_photo_24.Source = new BitmapImage(new Uri(GetPhoto(""), UriKind.RelativeOrAbsolute));
                                lb_staffno_24.Content = "";
                                lb_cardno_24.Content = "";
                                lb_name_24.Content = "";
                                lb_org_24.Content = "";
                                lb_job_24.Content = "";
                                lb_job_lev_24.Content = "";
                            }
                            Passages[i].Changed = false;
                        }
                    }
                }
                //第二行第5个
                for (int i = 0; i < 15; i++)
            {
                if (Passages[i] != null && Passages[i].PassageName == window_2_5)
                {
                    if (Passages[i].Changed)
                    {
                        if (Passages[i].LiveTime > 0)
                        {
                            img_photo_25.Source = new BitmapImage(new Uri(GetPhoto(Passages[i].photo), UriKind.RelativeOrAbsolute));
                            lb_staffno_25.Content = Passages[i].staffno;
                            lb_cardno_25.Content = Passages[i].cardno;
                            lb_name_25.Content = Passages[i].name;
                            lb_org_25.Content = Passages[i].org;
                            lb_job_25.Content = Passages[i].job;
                            lb_job_lev_25.Content = Passages[i].job_lev;
                        }
                        else
                        {
                            img_photo_25.Source = new BitmapImage(new Uri(GetPhoto(""), UriKind.RelativeOrAbsolute));
                            lb_staffno_25.Content = "";
                            lb_cardno_25.Content = "";
                            lb_name_25.Content = "";
                            lb_org_25.Content = "";
                            lb_job_25.Content = "";
                            lb_job_lev_25.Content = "";
                        }
                        Passages[i].Changed = false;
                    }
                }
            }
        }
            catch { }
        }

        //人数统计更新函数
        private void UpdateCount()
        {
            try
            {
                switch (re_swich)
                {
                    case 1:
                        lb_schedule_1.Content = "夜班：";
                        lb_starttime_3.Content = GetLeaderStaff(1);
                        //lb_schedule_2.Content = "";
                        //lb_schedule_3.Content = "";
                        //lb_starttime_2.Content = time_schedule[0].ToString();
                        //lb_endtime_2.Content = time_schedule[1].ToString();
                        //lb_incount_2.Content = incount_schedule[0] + "/" + incount_schedule[1];
                        //lb_outcount_2.Content = outcount_schedule[0] + "/" + outcount_schedule[1];
                        break;
                    case 2:
                        lb_schedule_1.Content = "早班：";
                        lb_starttime_3.Content = GetLeaderStaff(2);
                        //lb_schedule_2.Content = "";
                        //lb_schedule_3.Content = "晚班";
                        //lb_starttime_1.Content = time_schedule[0].ToString();
                        //lb_starttime_3.Content = time_schedule[1].ToString();
                        //lb_endtime_1.Content = time_schedule[1].ToString();
                        //lb_endtime_3.Content = time_schedule[2].ToString();
                        //lb_incount_1.Content = incount_schedule[0] + "/" + incount_schedule[1];
                        //lb_incount_3.Content = incount_schedule[2] + "/" + incount_schedule[3];
                        //lb_outcount_1.Content = outcount_schedule[0] + "/" + outcount_schedule[1];
                        //lb_outcount_3.Content = outcount_schedule[2] + "/" + outcount_schedule[3];
                        break;
                    case 3:
                        lb_schedule_1.Content = "中班：";
                        lb_starttime_3.Content = GetLeaderStaff(3);
                        //lb_schedule_2.Content = "中班";
                        //lb_schedule_3.Content = "晚班";
                        //lb_starttime_1.Content = time_schedule[0].ToString();
                        //lb_starttime_2.Content = time_schedule[1].ToString();
                        //lb_starttime_3.Content = time_schedule[2].ToString();
                        //lb_endtime_1.Content = time_schedule[1].ToString();
                        //lb_endtime_2.Content = time_schedule[2].ToString();
                        //lb_endtime_3.Content = time_schedule[3].ToString();
                        //lb_incount_1.Content = incount_schedule[0] + "/" + incount_schedule[1];
                        //lb_incount_2.Content = incount_schedule[2] + "/" + incount_schedule[3];
                        //lb_incount_3.Content = incount_schedule[4] + "/" + incount_schedule[5];
                        //lb_outcount_1.Content = outcount_schedule[0] + "/" + outcount_schedule[1];
                        //lb_outcount_2.Content = outcount_schedule[2] + "/" + outcount_schedule[3];
                        //lb_outcount_3.Content = outcount_schedule[4] + "/" + outcount_schedule[5];
                        break;
                    default:
                        break;
                }
            }
            catch { }
        }

        //门禁机状态更新函数
        private void UpdateStatus()
        {
            try
            {
                for (int i = 0; i < 15; i++)
                {
                    if (Passages[i] != null && Passages[i].PassageName == window_1_1)
                    {
                        lb_tile_1.Content = Passages[i].PassageName;
                        if (Passages[i].InOut == "1")
                        {
                            bd_title_1.Background = System.Windows.Media.Brushes.Orange;
                        }
                        else if (Passages[i].InOut == "2")
                        {
                            bd_title_1.Background = System.Windows.Media.Brushes.LightBlue;
                        }
                        else
                        {
                            bd_title_1.Background = System.Windows.Media.Brushes.LightGray;
                        }
                        if (Passages[i].Status)
                        {
                            img_green_1.Visibility = Visibility.Visible;
                            img_red_1.Visibility = Visibility.Hidden;
                        }
                        else
                        {
                            img_red_1.Visibility = Visibility.Visible;
                            img_green_1.Visibility = Visibility.Hidden;
                        }
                    }
                }

                for (int i = 0; i < 15; i++)
                {
                    if (Passages[i] != null && Passages[i].PassageName == window_1_2)
                    {
                        lb_tile_2.Content = Passages[i].PassageName;
                        if (Passages[i].InOut == "1")
                        {
                            bd_title_2.Background = System.Windows.Media.Brushes.Orange;
                        }
                        else if (Passages[i].InOut == "2")
                        {
                            bd_title_2.Background = System.Windows.Media.Brushes.LightBlue;
                        }
                        else
                        {
                            bd_title_2.Background = System.Windows.Media.Brushes.LightGray;
                        }
                        if (Passages[i].Status)
                        {
                            img_green_2.Visibility = Visibility.Visible;
                            img_red_2.Visibility = Visibility.Hidden;
                        }
                        else
                        {
                            img_red_2.Visibility = Visibility.Visible;
                            img_green_2.Visibility = Visibility.Hidden;
                        }
                    }
                }
                for (int i = 0; i < 15; i++)
                {
                    if (Passages[i] != null && Passages[i].PassageName == window_1_3)
                    {
                        lb_tile_3.Content = Passages[i].PassageName;
                        if (Passages[i].InOut == "1")
                        {
                            bd_title_3.Background = System.Windows.Media.Brushes.Orange;
                        }
                        else if (Passages[i].InOut == "2")
                        {
                            bd_title_3.Background = System.Windows.Media.Brushes.LightBlue;
                        }
                        else
                        {
                            bd_title_3.Background = System.Windows.Media.Brushes.LightGray;
                        }
                        if (Passages[i].Status)
                        {
                            img_green_3.Visibility = Visibility.Visible;
                            img_red_3.Visibility = Visibility.Hidden;
                        }
                        else
                        {
                            img_red_3.Visibility = Visibility.Visible;
                            img_green_3.Visibility = Visibility.Hidden;
                        }
                    }
                }

                    for (int i = 0; i < 15; i++)
                    {
                        if (Passages[i] != null && Passages[i].PassageName == window_1_4)
                        {
                            lb_tile_4.Content = Passages[i].PassageName;
                            if (Passages[i].InOut == "1")
                            {
                                bd_title_4.Background = System.Windows.Media.Brushes.Orange;
                            }
                            else if (Passages[i].InOut == "2")
                            {
                                bd_title_4.Background = System.Windows.Media.Brushes.LightBlue;
                            }
                            else
                            {
                                bd_title_4.Background = System.Windows.Media.Brushes.LightGray;
                            }
                            if (Passages[i].Status)
                            {
                                img_green_4.Visibility = Visibility.Visible;
                                img_red_4.Visibility = Visibility.Hidden;
                            }
                            else
                            {
                                img_red_4.Visibility = Visibility.Visible;
                                img_green_4.Visibility = Visibility.Hidden;
                            }
                        }
                    }
            for (int i = 0; i < 15; i++)
            {
                if (Passages[i] != null && Passages[i].PassageName == window_1_5)
                {
                    lb_tile_15.Content = Passages[i].PassageName;
                    if (Passages[i].InOut == "1")
                    {
                        bd_title_15.Background = System.Windows.Media.Brushes.Orange;
                    }
                    else if (Passages[i].InOut == "2")
                    {
                        bd_title_15.Background = System.Windows.Media.Brushes.LightBlue;
                    }
                    else
                    {
                        bd_title_15.Background = System.Windows.Media.Brushes.LightGray;
                    }
                    if (Passages[i].Status)
                    {
                        img_green_15.Visibility = Visibility.Visible;
                        img_red_15.Visibility = Visibility.Hidden;
                    }
                    else
                    {
                        img_red_15.Visibility = Visibility.Visible;
                        img_green_15.Visibility = Visibility.Hidden;
                    }
                }
            }
            for (int i = 0; i < 15; i++)
                    {
                        if (Passages[i] != null && Passages[i].PassageName == window_2_1)
                        {
                            lb_tile_21.Content = Passages[i].PassageName;
                            if (Passages[i].InOut == "1")
                            {
                                bd_title_21.Background = System.Windows.Media.Brushes.Orange;
                            }
                            else if (Passages[i].InOut == "2")
                            {
                                bd_title_21.Background = System.Windows.Media.Brushes.LightBlue;
                            }
                            else
                            {
                                bd_title_21.Background = System.Windows.Media.Brushes.LightGray;
                            }
                            if (Passages[i].Status)
                            {
                                img_green_21.Visibility = Visibility.Visible;
                                img_red_21.Visibility = Visibility.Hidden;
                            }
                            else
                            {
                                img_red_21.Visibility = Visibility.Visible;
                                img_green_21.Visibility = Visibility.Hidden;
                            }
                        }
                    }

                    for (int i = 0; i < 15; i++)
                    {
                        if (Passages[i] != null && Passages[i].PassageName == window_2_2)
                        {
                            lb_tile_22.Content = Passages[i].PassageName;
                            if (Passages[i].InOut == "1")
                            {
                                bd_title_22.Background = System.Windows.Media.Brushes.Orange;
                            }
                            else if (Passages[i].InOut == "2")
                            {
                                bd_title_22.Background = System.Windows.Media.Brushes.LightBlue;
                            }
                            else
                            {
                                bd_title_22.Background = System.Windows.Media.Brushes.LightGray;
                            }
                            if (Passages[i].Status)
                            {
                                img_green_22.Visibility = Visibility.Visible;
                                img_red_22.Visibility = Visibility.Hidden;
                            }
                            else
                            {
                                img_red_22.Visibility = Visibility.Visible;
                                img_green_22.Visibility = Visibility.Hidden;
                            }
                        }
                    }

                    for (int i = 0; i < 15; i++)
                    {
                        if (Passages[i] != null && Passages[i].PassageName == window_2_3)
                        {
                            lb_tile_23.Content = Passages[i].PassageName;
                            if (Passages[i].InOut == "1")
                            {
                                bd_title_23.Background = System.Windows.Media.Brushes.Orange;
                           }
                           else if (Passages[i].InOut == "2")
                           {
                               bd_title_23.Background = System.Windows.Media.Brushes.LightBlue;
                           }
                           else
                           {
                               bd_title_23.Background = System.Windows.Media.Brushes.LightGray;
                           }
                           if (Passages[i].Status)
                           {
                               img_green_23.Visibility = Visibility.Visible;
                               img_red_23.Visibility = Visibility.Hidden;
                           }
                           else
                           {
                               img_red_23.Visibility = Visibility.Visible;
                               img_green_23.Visibility = Visibility.Hidden;
                           }
                       }
                   }
                   for (int i = 0; i < 15; i++)
                   {
                       if (Passages[i] != null && Passages[i].PassageName == window_2_4)
                       {
                           lb_tile_24.Content = Passages[i].PassageName;
                           if (Passages[i].InOut == "1")
                           {
                               bd_title_24.Background = System.Windows.Media.Brushes.Orange;
                           }
                           else if (Passages[i].InOut == "2")
                           {
                               bd_title_24.Background = System.Windows.Media.Brushes.LightBlue;
                           }
                           else
                           {
                               bd_title_24.Background = System.Windows.Media.Brushes.LightGray;
                           }
                           if (Passages[i].Status)
                           {
                               img_green_24.Visibility = Visibility.Visible;
                               img_red_24.Visibility = Visibility.Hidden;
                           }
                           else
                           {
                               img_red_24.Visibility = Visibility.Visible;
                               img_green_24.Visibility = Visibility.Hidden;
                           }
                       }
                   }

            for (int i = 0; i < 15; i++)
            {
                if (Passages[i] != null && Passages[i].PassageName == window_2_5)
                {
                    lb_tile_25.Content = Passages[i].PassageName;
                    if (Passages[i].InOut == "1")
                    {
                        bd_title_25.Background = System.Windows.Media.Brushes.Orange;
                    }
                    else if (Passages[i].InOut == "2")
                    {
                        bd_title_25.Background = System.Windows.Media.Brushes.LightBlue;
                    }
                    else
                    {
                        bd_title_25.Background = System.Windows.Media.Brushes.LightGray;
                    }
                    if (Passages[i].Status)
                    {
                        img_green_25.Visibility = Visibility.Visible;
                        img_red_25.Visibility = Visibility.Hidden;
                    }
                    else
                    {
                        img_red_25.Visibility = Visibility.Visible;
                        img_green_25.Visibility = Visibility.Hidden;
                    }
                }
            }
        }
            catch { }
        }

        //时间更新函数
        private void UpdateTime()
        {
            try
            {
                DateTime now = DateTime.Now;
                lb_Date.Content = now.ToString("yyyy年MM月dd日HH:mm:ss dddd  ");
                //lb_Time.Content = now.ToString("HH:mm:ss  dddd");
                down_staffno.Content = staffdt.Rows.Count;
                return;
            }
            catch { }
        }

        //消息框更新函数
        private void UpdateMessage()
        {
            try
            {
                if (MsgQue.Count > 0)
                {
                    //lb_Message.Content = MsgQue.Dequeue();
                    //lb_Message.Background = System.Windows.Media.Brushes.Red;
                    MsgLiveTime = LiveTime + 1;
                }
                else
                {
                    //lb_Message.Content = string.Empty;
                    //lb_Message.Background = System.Windows.Media.Brushes.Transparent;
                    MsgLiveTime = 0;
                }
            }
            catch { }
        }

        //时间更新定时器
        private void TimeTimer(object obj)
        {
            staffdt = DB_SQLServer.ExecuteDataTable("SELECT t.staffname,t.deptname,t.beaconname,CONVERT(VARCHAR(30), t.intime, 120) AS intime,t.InBeaconName inbeaconname ,t.tagmac FROM view_pp_timestaff t ORDER BY intime DESC");
            new Thread(() =>
            {
                this.Dispatcher.Invoke(new Action(UpdateTime));
            }).Start();

            if (MsgLiveTime > 0)
            {
                MsgLiveTime--;
                if (MsgLiveTime == 0)
                {
                    new Thread(() =>
                    {
                        this.Dispatcher.Invoke(new Action(UpdateMessage));
                    }).Start();
                }
            }

            bool refresh = false;
            for (int i = 0; i < 15; i++)
            {
                if (Passages[i] != null)
                {
                    if (Passages[i].LiveTime > 0)
                    {
                        Passages[i].LiveTime--;
                        if (Passages[i].LiveTime == 0)
                        {
                            Passages[i].Changed = true;
                            refresh = true;
                        }
                    }
                }
            }

            if (refresh)
            {
                new Thread(() =>
                {
                    this.Dispatcher.Invoke(new Action(UpdateUI));
                }).Start();
            }
        }

        //播放语音
        private void PlayVoice(object obj)
        {
            try
            {
                string str = obj as string;
                if (spVoice)
                    spVoice.Speak(str);
            }
            catch { }
        }

        //解析从门禁采集端收到的消息
        private void ParseMessage(byte[] bReceive)
        {
            try
            {
                string strReceive = Encoding.GetEncoding("utf-8").GetString(bReceive, 0, bReceive.Length);  //利用Encoding类可以把字符串与字节数组互相转换
                if (strReceive.Substring(0,6) == "RECORD")    //String.SubString(int index,int length)   index: 开始位置，从0开始  length:你要取的子字符串的长度
                {
                    string[] arr_Msg = strReceive.Substring(8, strReceive.Length - 9).Split(new char[] { '\t' });  //Split(char [] ) 基于数组中的字符将字符串拆分为多个子字符串。

                    if (arr_Msg.Length < 9)
                    {
                        return;
                    }
                    string time = arr_Msg[0];
                    bool IsRealTime = true;
                    if ((DateTime.Now - DateTime.Parse(time)).TotalSeconds > 600)
                    {
                        IsRealTime = false;
                    }
                    int passno = int.Parse(arr_Msg[1]);   //Parse(string ) 将数字的字符串表示形式转换为它的等效 64 位有符号整数。
                    /****************防止溢栈***************/
                    //if (passno > 8)
                    //{
                    //    passno = 8;
                    //}
                    /*********************************************/
                    if (Passages[passno] == null)
                    {
                        return;
                    }
                    if (IsRealTime)
                    {
                        if ((Passages[passno].staffno == arr_Msg[2]) && (Passages[passno].LiveTime > 0))
                        {
                            ShowMessage("重复刷卡");
                            return;
                        }
                        Passages[passno].staffno = arr_Msg[2];
                        Passages[passno].cardno = arr_Msg[3];
                        Passages[passno].name = arr_Msg[4];
                        Passages[passno].org = arr_Msg[5];
                        Passages[passno].job = arr_Msg[6];
                        Passages[passno].job_lev = arr_Msg[7];
                        Passages[passno].photo = arr_Msg[8].Replace('\\', '/');  // string Replace(char oldChar, char newChar)  返回一个新字符串，其中此实例中出现的所有指定 Unicode 字符都替换为另一个指定的 Unicode 字符
                        Passages[passno].LiveTime = LiveTime + 1;
                        Passages[passno].Changed = true;
                        
                        new Thread(() =>
                        {
                            this.Dispatcher.Invoke(new Action(UpdateUI));
                        }).Start();

                        if (Passages[passno].InOut == "1")
                        {
                            SpeakMessage("欢迎" + Passages[passno].name);
                        }
                        else if (Passages[passno].InOut == "2")
                        {
                            SpeakMessage(Passages[passno].name + "再见");
                        }
                    }
                }
                else if (strReceive.Substring(0, 6) == "STATUS")
                {
                    bool refresh = false;
                    string[] arr_Msg = strReceive.Substring(8, strReceive.Length - 9).Split(new char[] { '\t' });
                    int DeviceCount = int.Parse(arr_Msg[0]);
                    if (arr_Msg.Length < 3 * DeviceCount + 1)
                    {
                        return;
                    }
                    //防止溢栈*********************
                    //if (DeviceCount > 8)
                    //{
                    //    DeviceCount = 8;
                    //}
                    /************************************/
                    for (int i = 0; i < DeviceCount; i++)
                    {
                        if (Passages[i] == null)
                        {
                            Passages[i] = new Passage();
                            Passages[i].PassageName = arr_Msg[3 * i + 1];
                            Passages[i].InOut = arr_Msg[3 * i + 2];
                            Passages[i].Changed = false;
                            Passages[i].Status = (int.Parse(arr_Msg[3 * i + 3]) > 0);
                            refresh = true;
                        }
                        else
                        {
                            if (Passages[i].PassageName != arr_Msg[3 * i + 1])
                            {
                                Passages[i].PassageName = arr_Msg[3 * i + 1];
                                Passages[i].InOut = arr_Msg[3 * i + 2];
                                refresh = true;
                            }

                            if (Passages[i].Status != (int.Parse(arr_Msg[3 * i + 3]) > 0))
                            {
                                Passages[i].Status = (int.Parse(arr_Msg[3 * i + 3]) > 0);
                                refresh = true;
                            }
                        }
                    }

                    if (refresh)
                    {
                        BeaconList = string.Empty;
                        for (int i = 0; i < DeviceCount; i++)
                        {
                            BeaconList += "'" + Passages[i].PassageName + "'";
                            if (i < DeviceCount - 1)
                            {
                                BeaconList += ',';
                            }
                        }
                        new Thread(() =>
                        {
                            this.Dispatcher.Invoke(new Action(UpdateStatus));
                        }).Start();
                    }
                }
            }
            catch { }
        }

        //计算班次时间
        private void GetScheduleTime()
        {
            DateTime t0 = DateTime.Now;
            if ((time_schedule.Count == 0) || (t0 >= time_schedule[time_schedule.Count - 1]) || (t0 < time_schedule[0]))
            {
                time_schedule.Clear();
                incount_schedule.Clear();
                outcount_schedule.Clear();
                for (int i = 0; i < list_schedule.Count; i++)
                {
                    incount_schedule.Add(0);
                    incount_schedule.Add(0);
                    outcount_schedule.Add(0);
                    outcount_schedule.Add(0);
                }
            }
            else
            {
                return;
            }
            if (t0 < new DateTime(t0.Year, t0.Month, t0.Day, list_schedule[0].hour, list_schedule[0].minute, 0))
            {
                t0 = t0.AddDays(-1);
            }
            if (list_schedule.Count == 1)
            {
                time_schedule.Add(new DateTime(t0.Year, t0.Month, t0.Day, list_schedule[0].hour, list_schedule[0].minute, 0));
                time_schedule.Add(new DateTime(t0.AddDays(1).Year, t0.AddDays(1).Month, t0.AddDays(1).Day, list_schedule[0].hour, list_schedule[0].minute, 0));
            }
            else if (list_schedule.Count == 2)
            {
                time_schedule.Add(new DateTime(t0.Year, t0.Month, t0.Day, list_schedule[0].hour, list_schedule[0].minute, 0));
                time_schedule.Add(new DateTime(t0.Year, t0.Month, t0.Day, list_schedule[1].hour, list_schedule[1].minute, 0));
                time_schedule.Add(new DateTime(t0.AddDays(1).Year, t0.AddDays(1).Month, t0.AddDays(1).Day, list_schedule[0].hour, list_schedule[0].minute, 0));
            }
            else
            {
                time_schedule.Add(new DateTime(t0.Year, t0.Month, t0.Day, list_schedule[0].hour, list_schedule[0].minute, 0));
                time_schedule.Add(new DateTime(t0.Year, t0.Month, t0.Day, list_schedule[1].hour, list_schedule[1].minute, 0));
                time_schedule.Add(new DateTime(t0.Year, t0.Month, t0.Day, list_schedule[2].hour, list_schedule[2].minute, 0));
                time_schedule.Add(new DateTime(t0.AddDays(1).Year, t0.AddDays(1).Month, t0.AddDays(1).Day, list_schedule[0].hour, list_schedule[0].minute, 0));
            }
        }

        //从数据库读取人数统计
        public void GetCount(object obj)
        {
            try
            {
                GetScheduleTime();
                //for (int i = 0; i < list_schedule.Count; i++)
                //{
                //    if (BeaconList.Length > 0)
                //    {
                //        incount_schedule[2 * i] = Convert.ToInt32(DB_SQLServer.ExecuteScalar(string.Format("SELECT COUNT(DISTINCT pa.[StaffNo]) FROM [T_PP_AccessControl] pa INNER JOIN [T_JC_Beacon] jb ON pa.[BeaMac] = jb.[BeaMac] WHERE jb.[BeaType] = 'JZWZLY004' AND (pa.[Time] BETWEEN '{0}' AND '{1}') AND jb.[BeaconName] in ({2})", time_schedule[i], time_schedule[i + 1], BeaconList)));
                //        outcount_schedule[2 * i] = Convert.ToInt32(DB_SQLServer.ExecuteScalar(string.Format("SELECT COUNT(DISTINCT pa.[StaffNo]) FROM [T_PP_AccessControl] pa INNER JOIN [T_JC_Beacon] jb ON pa.[BeaMac] = jb.[BeaMac] WHERE jb.[BeaType] = 'JZWZLY005' AND (pa.[Time] BETWEEN '{0}' AND '{1}') AND jb.[BeaconName] in ({2})", time_schedule[i], time_schedule[i + 1], BeaconList)));
                //    }
                    
                //    incount_schedule[2 * i + 1] = Convert.ToInt32(DB_SQLServer.ExecuteScalar(string.Format("SELECT COUNT(DISTINCT pa.[StaffNo]) FROM [T_PP_AccessControl] pa INNER JOIN [T_JC_Beacon] jb ON pa.[BeaMac] = jb.[BeaMac] WHERE jb.[BeaType] = 'JZWZLY004' AND (pa.[Time] BETWEEN '{0}' AND '{1}')", time_schedule[i], time_schedule[i + 1])));
                //    outcount_schedule[2 * i + 1] = Convert.ToInt32(DB_SQLServer.ExecuteScalar(string.Format("SELECT COUNT(DISTINCT pa.[StaffNo]) FROM [T_PP_AccessControl] pa INNER JOIN [T_JC_Beacon] jb ON pa.[BeaMac] = jb.[BeaMac] WHERE jb.[BeaType] = 'JZWZLY005' AND (pa.[Time] BETWEEN '{0}' AND '{1}')", time_schedule[i], time_schedule[i + 1])));
                //}
                new Thread(() =>
                {
                    this.Dispatcher.Invoke(new Action(Computing_shifts));
                    this.Dispatcher.Invoke(new Action(UpdateCount));
                }).Start();
                
            }
            catch { }
        }

        //在消息框显示消息
        public void ShowMessage(string msgstr)
        {
            string dispstr = msgstr.Substring(0, msgstr.Length / 2) + "\n" + msgstr.Substring(msgstr.Length / 2, msgstr.Length - msgstr.Length / 2);
            MsgQue.Enqueue(dispstr);
            new Thread(() =>
            {
                this.Dispatcher.Invoke(new Action(UpdateMessage));
            }).Start();
        }

        //语音播放消息
        public void SpeakMessage(string msgstr)
        {
            if (b_PlayVoice)
            {
                Thread Play_Thread = new Thread(new ParameterizedThreadStart(PlayVoice));
                Play_Thread.IsBackground = true;
                Play_Thread.Start(msgstr);
            }
        }

        //计算当前班次
        public void Computing_shifts()
        {

            //获取当前系统时间并判断是否为服务时间
            TimeSpan nowDt = DateTime.Now.TimeOfDay;

            TimeSpan workStartDT1 = DateTime.Parse("00:00").TimeOfDay;
            TimeSpan workEndDT1 = DateTime.Parse("07:59").TimeOfDay;

            TimeSpan workStartDT2 = DateTime.Parse("16:00").TimeOfDay;
            TimeSpan workEndDT2 = DateTime.Parse("23:59").TimeOfDay;

            if ((nowDt > workStartDT1) && (nowDt < workEndDT1))
            {
                re_swich = 1;//晚班
            }
            else if ((nowDt > workEndDT1) && (nowDt < workStartDT2))
            {
                re_swich = 2;//早班
            }
            else
            {
                re_swich = 3;//中班
            }
            //string newTime = DateTime.Now.ToLongTimeString().ToString();
            //string[] NewTime = newTime.Split(new char[1] { ':' });
            //long newTime_s = long.Parse(NewTime[0]) * 60 * 60 + long.Parse(NewTime[1]) * 60 + long.Parse(NewTime[2]);
            //if (newTime_s >= Com_time[0] && newTime_s < Com_time[1])
            //{
            //    re_swich = 2;
            //}
            //else if (newTime_s >= Com_time[1] && newTime_s < Com_time[2])
            //{
            //    re_swich = 3;
            //}
            //else
            //{
            //    re_swich = 1;
            //}



        }

        //人员信息更新定时器
        private void StaffTimer(object obj)
        {
            n = 0;
            Staff_dt = null;
            Staff_dt = DB_SQLServer.ExecuteDataTable("SELECT t.staffname,t.deptname,t.beaconname,CONVERT(VARCHAR(30), t.intime, 120) AS intime,t.InBeaconName inbeaconname ,t.tagmac FROM view_pp_timestaff t ORDER BY intime DESC");
            if (Staff_dt.Rows.Count > 100)
            {
                for (; n < 100; n++)
                {
                    new Thread(() =>
                    {
                        this.Dispatcher.Invoke(new Action(GetStaff));
                    }).Start();
                    Thread.Sleep(2000);                   
                }
            }
            else
            {
                for (; n < Staff_dt.Rows.Count; n++)
                {
                    new Thread(() =>
                    {
                        this.Dispatcher.Invoke(new Action(GetStaff));
                    }).Start();
                    Thread.Sleep(2000);
                }
            }
                    
        }
        public void GetStaff()
        {
            //DataTable dt = DB_SQLServer.ExecuteDataTable("SELECT t.staffname,t.deptname,t.beaconname,CONVERT(VARCHAR(30), t.intime, 120) AS intime,t.InBeaconName inbeaconname FROM view_pp_timestaff t ORDER BY intime DESC");
            //down_staffno.Content = dt.Rows.Count;
            //for (int i = 0; i<dt.Rows.Count; i++)
            //{
            //    staff_name.Content = dt.Rows[i][0];
            //    staff_section.Content = dt.Rows[i][1];
            //    cu_base.Content = dt.Rows[i][2];
            //    down_time.Content = dt.Rows[i][3];
            //    down_place.Content = dt.Rows[i][4];
            //}
            if (n < 100)
            {
                

                staff_name.Content = Staff_dt.Rows[n][0];
                staff_section.Content = Staff_dt.Rows[n][1];
                cu_base.Content = Staff_dt.Rows[n][2];
                down_time.Content = Staff_dt.Rows[n][3];
                down_place.Content = Staff_dt.Rows[n][4];
                PinID.Content = Staff_dt.Rows[n][5];
            }
            else
            {
                return;
            }
            
        }

        public string GetLeaderStaff(int num)
        {
            string leadername = "";
            DataTable dt_leader = DB_SQLServer.ExecuteDataTable("SELECT staffid FROM T_JC_LEADERCLASS WHERE classdate = CONVERT(varchar(10),GETDATE(), 120);");
            for (int  i = 0; i < dt_leader.Rows.Count; i++)
            {
                try
                {
                    string[] NewTime = dt_leader.Rows[i][0].ToString().Split(new char[1] { ',' });
                    if (NewTime.Length > 0)
                    {
                        DataTable dt_leader_1 = DB_SQLServer.ExecuteDataTable(string.Format("SELECT StaffName FROM T_SM_Staff WHERE StaffID = '{0}'", NewTime[num-1]));

                        leadername = dt_leader_1.Rows[0][0].ToString();
                        
                    }
                }
                catch (Exception)
                {

                    throw;
                }
            }
            return leadername;

        }
    }
}
